# -*- coding: utf-8 -*-

import threading
import time


def target1():
    """目标函数"""
    if lock1.acquire(blocking=True):
        print('%s:%s' % (threading.currentThread().getName(), 'lock1.acquire',))

        # 睡眠(模拟业务)
        time.sleep(1)

        if lock2.acquire(blocking=True):
            print('%s:%s' % (threading.currentThread().getName(), 'lock2.acquire',))

            # 睡眠(模拟业务)
            time.sleep(1)

            lock2.release()
            print('%s:%s' % (threading.currentThread().getName(), 'lock2.release',))

        lock1.release()
        print('%s:%s' % (threading.currentThread().getName(), 'lock1.release',))

    pass


def target2():
    """目标函数"""
    if lock2.acquire(blocking=True):
        print('%s:%s' % (threading.currentThread().getName(), 'lock2.acquire',))

        # 睡眠(模拟业务)
        time.sleep(1)

        if lock1.acquire(blocking=True):
            print('%s:%s' % (threading.currentThread().getName(), 'lock1.acquire',))

            # 睡眠
            time.sleep(1)

            lock1.release()
            print('%s:%s' % (threading.currentThread().getName(), 'lock1.release',))

        lock2.release()
        print('%s:%s' % (threading.currentThread().getName(), 'lock2.release',))

    pass


# 创建互斥锁，默认未上锁
lock1 = threading.Lock()
lock2 = threading.Lock()


def deal_lock():
    """死锁现象：多个锁嵌套使用"""
    # 以目标函数作为参数创建线程

    thread1 = threading.Thread(target=target1)
    thread1.start()

    thread2 = threading.Thread(target=target2)
    thread2.start()


if __name__ == '__main__':
    deal_lock()
    pass
